﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CNotebook;
using CNotebook.Inventory;

namespace NotebookS2
{
    public partial class WHTransferOut : DevExpress.XtraBars.Ribbon.RibbonForm
    {
        public WHTransferOut()
        {
            InitializeComponent();
        }
        
        public string ConnectionString { get; set; }
        public string ActiveUserID { get; set; }
        public DataTable LineItems { get; set; }

        #region Function
        public void PrintPreview()
        {
            PRNT_WTS oPrint = new PRNT_WTS();

            oPrint.ConnectionString = this.ConnectionString;
            oPrint.DocumentNumber = txtDocumentNumber.Text;

            oPrint.WindowState = FormWindowState.Maximized;
            oPrint.ShowDialog();
        }
        
        public void ShowSearch()
        {
            FND_WTS oSearchDocument = new FND_WTS();

            oSearchDocument.ConnectionString = this.ConnectionString;
            oSearchDocument.ShowDialog();

            string sDocumentNumber = oSearchDocument.DocumentNumber;


            if (sDocumentNumber != null || sDocumentNumber.Trim() != "")
            {
                WTManager oManager = new WTManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                DataRow oRow = oManager.GetWarehouseTransfer(sDocumentNumber);


                #region Header
                txtDocumentNumber.Text = oRow["DocNum"].ToString();
                txtStatus.Text = oRow["DocStatus"].ToString();

                dtPostDate.Value = Convert.ToDateTime(oRow["PostingDate"]);
                cboSource.SelectedValue = oRow["SourceWhCode"].ToString();
                cboDestination.SelectedValue = oRow["DestWhCode"].ToString();

                txtRemarks.Text         = oRow["Remarks"].ToString();
                txtDriver.Text          = oRow["Driver"].ToString();
                txtHelper.Text          = oRow["Helper"].ToString();

                txtDateCreated.Text     = oRow["DateCreated"].ToString();
                txtCreatedBy.Text       = oRow["CreatedBy"].ToString();
                txtDateModified.Text    = oRow["DateModified"].ToString();
                txtModifiedBy.Text      = oRow["ModifiedBy"].ToString();


                #endregion

                #region Line Items
                this.LineItems = oManager.GetLineItems(sDocumentNumber);
                gridControl1.DataSource = this.LineItems;
                gridControl1.Refresh();
                #endregion

                oManager.Close();

                btnAdd.Text = "Update";

                if (txtStatus.Text == "Draft")
                {
                    if (gridView1.RowCount <= 0)
                    {
                        gridView1.AddNewRow();
                    }
                }

            }

        }

        void InitializeSeries()
        {

            string ObjectType = "103";
            SeriesManager oSeries = new SeriesManager();
            oSeries.ConnectionString = this.ConnectionString;
            oSeries.Open();
            if (oSeries.IsAutoNumber(ObjectType) == true)
            {
                txtDocumentNumber.Properties.ReadOnly = true;
                txtDocumentNumber.Text = "##########";

            }
            oSeries.Close();


        }

        string GetNewSeries()
        {
            string _SERIES = "";
            string _OBJECT_TYPE = "103";

            SeriesManager oSeries = new SeriesManager();
            oSeries.ConnectionString = this.ConnectionString;
            oSeries.Open();
            if (oSeries.IsAutoNumber(_OBJECT_TYPE) == true)
            {
                _SERIES = oSeries.GetNewSeries(_OBJECT_TYPE);
            }
            else
            {
                _SERIES = txtDocumentNumber.Text;
            }
            oSeries.Close();

            return _SERIES;
        }

        void RemoveBlankLastRowFirst()
        {
            int iCount = -1;
            gridView1.MoveLast();

            int[] oRow = gridView1.GetSelectedRows();

            iCount = oRow[0];
            string sItemCode = "";


            sItemCode = gridView1.GetRowCellValue(iCount, gridView1.Columns["ItemCode"]).ToString();

            if (sItemCode.Trim() == "")
            {
                gridView1.DeleteRow(iCount);
            }
        }

        DataTable GetLineTable()
        {
            DataTable _table = new DataTable();

            _table.Columns.Add("ItemCode", typeof(string));
            _table.Columns.Add("BarCode", typeof(string));
            _table.Columns.Add("ItemName", typeof(string));
            _table.Columns.Add("Qty", typeof(string));
            _table.Columns.Add("UnitCost", typeof(string));
            _table.Columns.Add("UoM", typeof(string));
            _table.Columns.Add("LotNumber", typeof(string));
            _table.Columns.Add("ExpiryDate", typeof(DateTime));
            _table.Columns.Add("MfrDate", typeof(DateTime));

            return _table;
        }

        void BindWarehouse()
        {
            WarehouseManager oManager = new WarehouseManager();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();


            cboSource.DataSource = oManager.GetWarehouse();
            cboSource.DisplayMember = "Dscription";
            cboSource.ValueMember = "Code";

            cboSource.Refresh();


            oManager.Close();
        }

        void BindWarehouseAndExclude(string _ExcludeWarehouse)
        {
            WarehouseManager oManager = new WarehouseManager();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();


            cboDestination.DataSource = oManager.GetWarehouseAndExclude(_ExcludeWarehouse);
            cboDestination.DisplayMember = "Dscription";
            cboDestination.ValueMember = "Code";

            cboDestination.Refresh();


            oManager.Close();
        }

        void DisableControls()
        {
            dtPostDate.Enabled = false;
            cboSource.Enabled = false;
            cboDestination.Enabled = false;
            txtDocumentNumber.Properties.ReadOnly = true;
            txtRemarks.Properties.ReadOnly = true;
            txtDriver.Properties.ReadOnly = true;
            txtHelper.Properties.ReadOnly = true;

            foreach (DevExpress.XtraGrid.Columns.GridColumn oCol in gridView1.Columns)
            {
                oCol.OptionsColumn.AllowEdit = false;
            }
        }

        void EnableControls()
        {
            dtPostDate.Enabled = true;
            cboSource.Enabled = true;
            cboDestination.Enabled = true;
            
            txtRemarks.Properties.ReadOnly = false;
            txtDriver.Properties.ReadOnly = false;
            txtHelper.Properties.ReadOnly = false;

            foreach (DevExpress.XtraGrid.Columns.GridColumn oCol in gridView1.Columns)
            {
                if (oCol.Name == "Dscription" || oCol.Name == "UoM" || oCol.Name == "LotNumber" || oCol.Name == "ExpiryDate")
                {
                    oCol.OptionsColumn.AllowEdit = false;
                }
                else
                {
                    oCol.OptionsColumn.AllowEdit = true;
                }
            }
        }

        #endregion

        public int ObjectType { get { return 103; } }

        string ApplyAuthorization()
        {
            UserManager oManager = new UserManager();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            string iAccessType = oManager.GetAccessType(this.ObjectType, this.ActiveUserID);

            oManager.Close();

            switch (iAccessType)
            {
                case "Full Access":
                    FullAccess();
                    break;
                case "Read Only":
                    ApplyReadOnly();
                    break;
                case "No Access":
                    NoAccess();
                    break;
            }

            return iAccessType;
        }
        
        int ApplyReadOnly()
        {
            DisableControls();

            txtStatus.Properties.Buttons[0].Enabled = false;
            txtStatus.Properties.Buttons[1].Enabled = false;


            return 2;
        }

        int FullAccess()
        {
            txtStatus.Properties.Buttons[0].Enabled = true;
            txtStatus.Properties.Buttons[1].Enabled = true;

            return 1;
        }

        int NoAccess()
        {
            MessageBox.Show("You have no right to access this module!!!!", "Security Policy", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            return 3;

        }

        private void WHTransferOut_Load(object sender, EventArgs e)
        {
            #region Default
            txtCreatedBy.Text = this.ActiveUserID;
            txtDateCreated.Text = System.DateTime.Now.ToString();
            txtModifiedBy.Text = this.ActiveUserID;
            txtDateModified.Text = System.DateTime.Now.ToString();
            #endregion

            BindWarehouse();

            BindWarehouseAndExclude(cboSource.SelectedValue.ToString());

            this.LineItems = GetLineTable();
            gridControl1.DataSource = this.LineItems;
            gridControl1.Refresh();

            if (this.LineItems.Rows.Count == 0)
            {
                gridView1.AddNewRow();
            }
        }

        private void cboSource_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                dtPostDate.Value = System.DateTime.Now;
                BindWarehouseAndExclude(cboSource.SelectedValue.ToString());
                
            }
            catch
            {
            }
        }

        private void ribbonControl1_Click(object sender, EventArgs e)
        {

        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                WTManager oManager = new WTManager();
                
                #region Header

                RemoveBlankLastRowFirst();

                WTUnit oUnit = new WTUnit();

                if (btnAdd.Text == "Add")
                {
                    txtDocumentNumber.Text = GetNewSeries();
                    oUnit.DocumentNumber = txtDocumentNumber.Text;
                    oUnit.PostingDate = dtPostDate.Value;
                    oUnit.SourceWarehouse = cboSource.SelectedValue.ToString();
                    oUnit.DestinationWarehouse = cboDestination.SelectedValue.ToString();
                    oUnit.Remarks = txtRemarks.Text;
                    oUnit.Driver = txtDriver.Text;
                    oUnit.Helper = txtHelper.Text;

                    oUnit.DocumentStatus = txtStatus.Text;
                    oUnit.DateCreated = Convert.ToDateTime(txtDateCreated.Text);
                    oUnit.CreatedBy = txtCreatedBy.Text;
                    oUnit.DateModified = Convert.ToDateTime(txtDateModified.Text);
                    oUnit.ModifiedBy = txtModifiedBy.Text;

                    oUnit.LineItems = this.LineItems;

                    oManager.ConnectionString = this.ConnectionString;
                    oManager.Open();

                    System.Data.SqlClient.SqlException ex = oManager.AddTransfer(oUnit);
                    oManager.Close();

                    if (ex == null)
                    {
                        MessageBox.Show("Transfer successfully added!!!", "Update", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        btnAdd.Text = "Update";
                    }
                    else
                    {
                        MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }

                }
                else
                {
                    
                    oUnit.DocumentNumber = txtDocumentNumber.Text;
                    oUnit.PostingDate = dtPostDate.Value;
                    oUnit.SourceWarehouse = cboSource.SelectedValue.ToString();
                    oUnit.DestinationWarehouse = cboDestination.SelectedValue.ToString();
                    oUnit.Remarks = txtRemarks.Text;
                    oUnit.Driver = txtDriver.Text;
                    oUnit.Helper = txtHelper.Text;

                    oUnit.DocumentStatus = txtStatus.Text;
                    oUnit.DateCreated = Convert.ToDateTime(txtDateCreated.Text);
                    oUnit.CreatedBy = txtCreatedBy.Text;
                    oUnit.DateModified = Convert.ToDateTime(txtDateModified.Text);
                    oUnit.ModifiedBy = txtModifiedBy.Text;

                    oUnit.LineItems = this.LineItems;



                    oManager.ConnectionString = this.ConnectionString;
                    oManager.Open();

                    System.Data.SqlClient.SqlException ex = oManager.UpdateTransfer(oUnit);
                    oManager.Close();

                    if (ex == null)
                    {
                        MessageBox.Show("Transfer successfully updated!!!", "Update", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }

                #endregion
                
            }
            catch
            {
            }


        }

        private void btnSearchItemCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            GetStocksForIssuance oForm = new GetStocksForIssuance();

            oForm.WhsCode = cboSource.SelectedValue.ToString();
            oForm.WhsName = cboSource.Text;
            oForm.ConnectionString = this.ConnectionString;
            oForm.ShowDialog();

            int iRowHandle = gridView1.FocusedRowHandle;

            gridView1.SetRowCellValue(iRowHandle, gridView1.Columns["ItemCode"], oForm.ItemCode);
            gridView1.SetRowCellValue(iRowHandle, gridView1.Columns["BarCode"], "");
            gridView1.SetRowCellValue(iRowHandle, gridView1.Columns["ItemName"], oForm.ItemName);
            gridView1.SetRowCellValue(iRowHandle, gridView1.Columns["UoM"], oForm.UoM);
            gridView1.SetRowCellValue(iRowHandle, gridView1.Columns["Qty"], oForm.Qty);
            gridView1.SetRowCellValue(iRowHandle, gridView1.Columns["UnitCost"], oForm.ItemUnitCost);
            gridView1.SetRowCellValue(iRowHandle, gridView1.Columns["LotNumber"], oForm.InvLotNumber);
            gridView1.SetRowCellValue(iRowHandle, gridView1.Columns["ExpiryDate"], oForm.InvExpireDate);
            gridView1.SetRowCellValue(iRowHandle, gridView1.Columns["MfrDate"], oForm.InvMfrDate);

        }

        private void gridView1_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                int iCount = -1;
                int[] oRow = gridView1.GetSelectedRows();

                iCount = oRow[0];

                if (e.KeyCode == Keys.Delete)
                {
                    if (MessageBox.Show("Are you sure you want to delete this Row?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        gridView1.DeleteRow(iCount);

                        if (gridView1.RowCount <= 0)
                        {
                            gridView1.AddNewRow();
                        }
                    }
                }

                if (e.KeyCode == Keys.Down)
                {
                    if (gridView1.IsLastRow)
                    {
                        string sItemCode = "";
                        oRow = gridView1.GetSelectedRows();

                        iCount = oRow[0];
                        sItemCode = gridView1.GetRowCellValue(iCount, gridView1.Columns["ItemCode"]).ToString();

                        if (sItemCode != "")
                        {
                            gridView1.AddNewRow();
                        }
                    }
                }
            }
            catch
            {
            }
        }

        private void txtStatus_EditValueChanged(object sender, EventArgs e)
        {
            if (txtStatus.Text == "In-Transit")
            {
                btnAdd.Enabled = false;
                DisableControls();
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = false;

            }
            if (txtStatus.Text == "Draft")
            {
                btnAdd.Enabled = true;
                EnableControls();
                txtStatus.Properties.Buttons[0].Visible = true;
                txtStatus.Properties.Buttons[1].Visible = true;
            }

            if (txtStatus.Text == "Received" || txtStatus.Text == "Canceled")
            {
                btnAdd.Enabled = false;
                DisableControls();
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = false;
            }
        }

        private void txtStatus_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (txtStatus.Text == "Draft")
            {
                if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.OK)
                {
                    if (MessageBox.Show("Are you sure you to set to Transit-Mode?", "WTS", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                    {
                        WTManager oManager = new WTManager();

                        oManager.ConnectionString = this.ConnectionString;
                        oManager.Open();

                        oManager.ChangeToTransitMode(cboSource.SelectedValue.ToString(), txtDocumentNumber.Text);
                        txtStatus.Text = "In-Transit";
                        oManager.Close();
                        return;
                    }
                }

                if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Close)
                {
                    if (MessageBox.Show("Are you sure you want to cancel the document?", "WTS", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                    {
                        WTManager oManager = new WTManager();

                        oManager.ConnectionString = this.ConnectionString;
                        oManager.Open();

                        oManager.CancelDocument(txtDocumentNumber.Text);
                        txtStatus.Text = "Canceled";
                        oManager.Close();
                        return;
                    }
                }
            }


            if (txtStatus.Text == "In-Transit")
            {
                if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.OK)
                {
                    if (MessageBox.Show("Are you sure you to set to Received?", "WTS", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                    {
                        WTManager oManager = new WTManager();

                        oManager.ConnectionString = this.ConnectionString;
                        oManager.Open();

                        oManager.ChangeToReceived(cboDestination.SelectedValue.ToString(), txtDocumentNumber.Text);
                        txtStatus.Text = "Received";
                        oManager.Close();
                        return;
                    }
                }
            }
        }

        private void btnSearchItemCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                DevExpress.XtraEditors.ButtonEdit txtSearchItemCode = (DevExpress.XtraEditors.ButtonEdit)sender;
                StockManager oManager = new StockManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                DataTable dt = new DataTable();

                dt = oManager.GetAvailableStockByItemCode(cboSource.SelectedValue.ToString(), txtSearchItemCode.Text);
                
                oManager.Close();


                if (dt.Rows.Count > 0)
                {
                    DataRow oRow = dt.Rows[0];
                    int iFocuseRowIndex = gridView1.FocusedRowHandle;

                    txtSearchItemCode.Text = oRow["ItemCode"].ToString();

                    gridView1.SetRowCellValue(iFocuseRowIndex, gridView1.Columns["ItemName"], oRow["ItemName"].ToString());
                    gridView1.SetRowCellValue(iFocuseRowIndex, gridView1.Columns["BarCode"], oRow["BarCode"].ToString());
                    gridView1.SetRowCellValue(iFocuseRowIndex, gridView1.Columns["UoM"], oRow["UoM"].ToString());
                    
                    gridView1.FocusedColumn = gridView1.Columns["Qty"];
                    gridView1.ShowEditor();


                }
            }
            if (e.KeyCode == Keys.Tab)
            {
            }
        }

        private void xtraScrollableControl2_Click(object sender, EventArgs e)
        {

        }

        private void btnLotNumber_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            SEL_LOTNUMBER oForm = new SEL_LOTNUMBER();

            int iRowIndex = gridView1.FocusedRowHandle;

            oForm.ConnectionString = this.ConnectionString;
            oForm.ItemCode = gridView1.GetRowCellValue(iRowIndex, gridView1.Columns["ItemCode"]).ToString();
            oForm.WarehouseCode = cboSource.SelectedValue.ToString();
            oForm.ShowDialog();
            gridView1.SetRowCellValue(iRowIndex, gridView1.Columns["LotNumber"], oForm.SelectedLotNumber);
            gridView1.SetRowCellValue(iRowIndex, gridView1.Columns["ExpiryDate"], oForm.SelectedExpiryDate);

            

        }
    }
}
